import ApolloClient from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { onError } from 'apollo-link-error'
import { ApolloLink, from } from 'apollo-link'
import { getToken } from '@/libs/util'
import { getDomain } from '@/local_config.js'

export default (auth = false) => {
  const headers = {}
  const domain = getDomain()
  const Middleware = new ApolloLink((operation, forward) => {
    // request时对请求进行处理
    return forward(operation)
  })
  const Afterware = new ApolloLink((operation, forward) => {
    return forward(operation).map(response => {
      // 服务器返回数据
      return response
    })
  })
  const errorLink = onError(({ graphQLErrors, networkError }) => {
    if (graphQLErrors) {
      graphQLErrors.map(({ message, locations, path, validation }) => {
        if (!validation) {
          window.app.$Message.warning(message)
        } else {
          for (const key in validation) {
            if (validation.hasOwnProperty(key)) {
              const element = validation[key]
              window.app.$Message.warning(element[0])
            }
          }
        }

        console.log(
          `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
        )
      })
    }
    if (networkError) {
    }
  })
  if (auth) {
    const token = getToken()
    headers.Authorization = `Bearer ${token}`
  }
  const httpLink = new HttpLink({
    uri: `${domain}graphql`,
    headers
  })
  const cache = new InMemoryCache()
  return new ApolloClient({
    link: from([Middleware, Afterware, errorLink, httpLink]),
    cache
  })
}
